<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\AvatarRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;

class UsersController extends Controller
{
    public function profile(Request $request)
    {
        if (is_null($request->user())) {
            $this->failed('请先登录', 401);
        }
        $userInfo = $request->user();

        if (!Str::contains($userInfo->avatar, ["http://", "https://", "data:image"])) {
            $userInfo->avatar = env('APP_URL') . "storage" . DIRECTORY_SEPARATOR . $userInfo->avatar;
        }
        return $this->success($userInfo);
    }

    // 更新个人信息
    public function update(Request $request)
    {
        $request->user()->update($request->only(['mobile', 'nickname', 'name', 'sex', 'birthday', 'qq', 'email']));
        return $this->message('修改个人信息成功');
    }

    // 上传头像
    public function uploadAvatar(AvatarRequest $request)
    {
        $fileContent = $request->file("avatar");
        $path = Storage::disk("public")->put("avatars", $fileContent);
        $request->user()->update([
            'avatar' => $path
        ]);
        return $this->success($path);
    }
}
